/**
 * 运单管理列表页面
 * @author xiaoxujs
 */
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import Search from './components/Search'; // 搜索模块
import NullifyModule from './components/NullifyModule'; // 作废弹窗
import AddModule from './components/AddModule'; // 添加弹窗
import SupplementModule from './components/SupplementModule'; // 补单弹窗

import { tableActionButtonLayout } from '../../../assets/fun/tableActionButtonLayout';
import { sendStatusData } from '../../../assets/data';

import { ITlplTPlanPageList, ITlplTPlanPageListParams, ITlplTPlanPageListSearch } from '../../../type/WaybillManagement/api';
import { TablePaginationPosition } from '../../../type/antd';
import { getTlplTPlanDelete, getTlplTPlanPlanStart, getTlplTPlanPlanStop, postTlplTPlanPageList } from '../api';
import { IFenye } from '../../../type/commit';

import { ExclamationCircleFilled } from '@ant-design/icons';
import { Button, message, Modal, Table, TableProps } from 'antd';
import { TitleBox } from "../../../assets/style";
import { ListBox, WaybillManagementPageBox } from "./style";
import DictionaryItemStyleModule from '../../../components/DictionaryItemStyleModule';  // 字典项样式

const { confirm } = Modal;

const WaybillManagementPage = () => {
    const contentValue: TablePaginationPosition = "bottomCenter"; //位置
    const navigate = useNavigate();

    const [total, setTotal] = useState(0);
    const [paging, setPaging] = useState({ //分页
        currentPage: 1,
        pageSize: 10
    });
    const [listData, setListData] = useState<ITlplTPlanPageList[]>([]); // 列表数据
    const [addModuleShow, setAddModuleShow] = useState(false); // 添加 编辑 弹窗
    const [searchData, setSearchData] = useState<ITlplTPlanPageListSearch>(); // 筛选条件
    const [tableLoading, setTableLoading] = useState(false); //tableLoading
    const [nullifyModuleShow, setNullifyModuleShow] = useState(false); //作废弹窗
    const [clickId, setClickId] = useState<string>(); // 点击的id
    const [supplementModuleShow, setSupplementModuleShow] = useState(false); //补单弹窗

    const listFun = useCallback(async (params: ITlplTPlanPageListParams) => {
        setTableLoading(true);
        const { code, msg, data } = (await postTlplTPlanPageList(
            params
        )) as IFenye<ITlplTPlanPageList>;
        if (code === 20000) {
            setListData(data.records);
            setTotal(data.total);
            setPaging({
                currentPage: params.currentPage,
                pageSize: params.pageSize
            })
            setTableLoading(false);
        } else {
            message.error(msg);
        }
    }, []);

    useEffect(() => {
        const params = {
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }, [listFun])
    // 检索回调函数
    const handleSearchCallback = (data: ITlplTPlanPageListSearch) => {
        const params = {
            ...data,
            currentPage: 1,
            pageSize: 10
        };
        listFun(params);
        setSearchData(data);
    }
    //  添加回调
    const handleAddModuleCallback = () => {
        const params: ITlplTPlanPageListParams = {
            currentPage: 1,
            pageSize: 10,
            ...searchData,
        }
        listFun(params);
        setAddModuleShow(false)
    }
    // 删除
    const handleDelete = async (id: string) => {
        confirm({
            title: '确定要删除当前运单吗?',
            icon: <ExclamationCircleFilled />,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                const { code, msg } = await getTlplTPlanDelete({
                    planId: id,
                }) as { code: number; msg: string };
                if (code === 20000) {
                    message.success('删除成功');
                    const params: ITlplTPlanPageListParams = {
                        currentPage: paging.currentPage,
                        pageSize: paging.pageSize,
                        ...searchData,
                    }
                    listFun(params);
                } else {
                    message.error(msg);
                }
            },
        });
    }
    // 暂停
    const handleStop = async (id: string) => {
        confirm({
            title: '确定要暂停当前运单吗?',
            icon: <ExclamationCircleFilled />,
            okText: '暂停',
            cancelText: '取消',
            onOk: async () => {
                const { code, msg } = await getTlplTPlanPlanStop({
                    planId: id,
                }) as { code: number; msg: string };
                if (code === 20000) {
                    message.success('暂停成功');
                    const params: ITlplTPlanPageListParams = {
                        currentPage: paging.currentPage,
                        pageSize: paging.pageSize,
                        ...searchData,
                    }
                    listFun(params);
                } else {
                    message.error(msg);
                }
            },
        });
    }
    // 开始
    const handleStart = async (id: string) => {
        confirm({
            title: '确定要开始当前运单吗?',
            icon: <ExclamationCircleFilled />,
            okText: '开始',
            cancelText: '取消',
            onOk: async () => {
                const { code, msg } = await getTlplTPlanPlanStart({
                    planId: id,
                }) as { code: number; msg: string };
                if (code === 20000) {
                    message.success('运单开始');
                    const params: ITlplTPlanPageListParams = {
                        currentPage: paging.currentPage,
                        pageSize: paging.pageSize,
                        ...searchData,
                    }
                    listFun(params);
                } else {
                    message.error(msg);
                }
            },
        });
    }
    // 打开作废弹窗
    const handleNullify = (id: string) => {
        setNullifyModuleShow(true);
        setClickId(id);
    }
    // 作废弹窗回调
    const handleNullifyCallback = () => {
        setNullifyModuleShow(false);
        const params: ITlplTPlanPageListParams = {
            currentPage: paging.currentPage,
            pageSize: paging.pageSize,
            ...searchData,
        }
        listFun(params);
        setClickId(undefined);
    }
    // 打开补单弹窗
    const handleSupplement = (id: string) => {
        setSupplementModuleShow(true);
        setClickId(id);
    }
    // 补单弹窗回调
    const handleSupplementCallback = () => {
        const params: ITlplTPlanPageListParams = {
            currentPage: paging.currentPage,
            pageSize: paging.pageSize,
            ...searchData,
        }
        listFun(params);
        setSupplementModuleShow(false);
        setClickId(undefined);
    }
    // 进入导入车辆页面
    const handleEnterVehiclePage = (data: ITlplTPlanPageList) => {
        navigate('/home/waybillManagement/vehicleManagement', {
            state: {
                data
            }
        })
    }
    // 进入装车数据页面
    const handleEnterShippingPage = (data: ITlplTPlanPageList) => {
        navigate('/home/waybillManagement/shippingReport', {
            state: {
                data
            }
        })
    }

    const pagination = {
        //分页
        position: [contentValue],
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        // showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: paging.pageSize,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: total,
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current: number, pageSize: number) => {
            const params = {
                ...searchData,
                currentPage: current,
                pageSize: pageSize,
            }
            listFun(params);
        },
    };
    // 运单管理列表页面
    const columns: TableProps<ITlplTPlanPageList>['columns'] = [
        {
            title: '序号',
            align: 'center',
            render: (text, record, index) => <span>{(paging.currentPage * paging.pageSize) - paging.pageSize + index + 1}</span>,
        },
        {
            title: '收货单位',
            align: 'center',
            dataIndex: 'consignee',

        },
        {
            title: '装运周期',
            align: 'center',
            render: (text, record, index) => <span>{record.startDate + '~' + record.endDate}</span>,

        },
        {
            title: '货品名称',
            align: 'center',
            dataIndex: 'product',

        },
        {
            title: '总发运量(吨)',
            align: 'center',
            dataIndex: 'gross',

        },
        {
            title: '已发运量(吨)',
            align: 'center',
            dataIndex: 'sell',

        },
        {
            title: '执行状态',
            dataIndex: 'state',
            align: 'center',
            render: (text, record) => <DictionaryItemStyleModule
                dianColor={sendStatusData.color[text]}
                text={sendStatusData.text[text]}
                isTooltip={text === 3}
                tooltipText={record.reason}
            />

        },
        {
            title: '操作',
            align: 'center',
            render: (_, record) => {
                // 1.  导入车辆  作废不能导入
                // 2.  装车数据  一直都能看
                // 3.  补充计划量  作废不能点
                // 4.  开始  开始、作废不能点
                // 5.  暂停  未开始、暂停、作废不能点
                // 6.  作废  一直都能点
                // 7. （0：未开始，1：开始，2：暂停，3：作废）

                let daoruIf = false; // 导入车辆
                let biaojingIf = false; // 补充计划量
                let kaishiIf = false; // 开始
                let zantingIf = false; // 暂停
                let zuofeiIf = false; // 作废
                // 判断是否显示导入车辆
                if (record.state === 3) { // 如果当前作废
                    daoruIf = true;
                    biaojingIf = true;
                    kaishiIf = true;
                    zuofeiIf = true;
                } else if (record.state === 2) { // 如果当前暂停
                    zantingIf = true;
                } else if (record.state === 1) { // 如果当前开始
                    kaishiIf = true;
                } else if (record.state === 0) { // 如果当前未开始
                    zantingIf = true;
                }
                return <>
                    {
                        tableActionButtonLayout([
                            {
                                if: true,
                                buttonHtml: <Button type='link' disabled={daoruIf} onClick={() => handleEnterVehiclePage(record)}>导入车辆</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' onClick={() => handleEnterShippingPage(record)}>装车数据</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' disabled={biaojingIf} onClick={() => handleSupplement(record.id)}>补充计划量</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' disabled={kaishiIf} onClick={() => handleStart(record.id)}>开始</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' disabled={zantingIf} onClick={() => handleStop(record.id)}>暂停</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' disabled={zuofeiIf} onClick={() => handleNullify(record.id)}>作废</Button>
                            },
                            {
                                if: true,
                                buttonHtml: <Button type='link' onClick={() => handleDelete(record.id)}>删除</Button>
                            },

                        ])
                    }
                </>
            },
        },
    ];
    return <WaybillManagementPageBox>
        <TitleBox>
            运单管理
        </TitleBox>
        <Search handleSearchCallback={handleSearchCallback} />
        <ListBox>
            <div className='list_title_box'>
                <div className='list_title_text'>全部</div>
                <Button type='primary' icon={<span className="iconfont">&#xe620;</span>} onClick={() => setAddModuleShow(true)}>添加运单</Button>
            </div>
            <Table<ITlplTPlanPageList>
                columns={columns}
                dataSource={listData}
                rowKey='id'
                pagination={pagination}
                loading={tableLoading}
            />
        </ListBox>
        {/* 添加弹窗 */}
        <AddModule open={addModuleShow} handleAddModuleCallback={handleAddModuleCallback} />
        {/* 作废弹窗 */}
        <NullifyModule open={nullifyModuleShow} handleNullifyCallback={handleNullifyCallback} id={clickId} />
        {/* 补充计划量 */}
        <SupplementModule open={supplementModuleShow} handleSupplementCallback={handleSupplementCallback} id={clickId} />
    </WaybillManagementPageBox>

}

export default WaybillManagementPage;